package com.cyandpos.pad.cateringformat.choosemenu;

import android.app.AlertDialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.ConstantString;
import com.cyandpos.pad.common.commondata.DialogConstant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.OnDialogListener;
import com.cyandpos.pad.posdata.CyFood;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.QueryGoodParam;
import com.cyandpos.pad.sale.saleutils.SaleUtil;
import com.cyandpos.pad.sale.view.SelfNumKeyView;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.LogUtils;
import com.cyandpos.pad.utils.view.InputNumberDialogCommon;
import com.cyandpos.pad.utils.view.SelectFlavorDialog;

import java.util.ArrayList;
import java.util.List;

public class FoodOrderExpandableAdapter extends BaseExpandableListAdapter {
    private List<Goods> list;
    private Context context;
    private String content;
    private MenuFoodFragment fragment;
    private int index=-1;
    private AlertDialog mDialog;
    public FoodOrderExpandableAdapter(List<Goods> list, Context context,MenuFoodFragment fragment){
        this.list=list;
        this.context=context;
        this.fragment= fragment;

    }
    @Override
    public int getGroupCount() {
        return list.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return 1;
    }

    @Override
    public Goods getGroup(int i) {
        return list.get(i);
    }

    @Override
    public Goods getChild(int i, int i1) {
        return list.get(i);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        GroupHolder groupHolder;
        if(view==null){
            groupHolder=new GroupHolder();
            view= LayoutInflater.from(context).inflate(R.layout.item_food_order,null);
            groupHolder.tv_number=view.findViewById(R.id.tv_number);
            groupHolder.tv_name=view.findViewById(R.id.tv_name);
            groupHolder.img_sale_goods_cut=view.findViewById(R.id.img_sale_goods_cut);
            groupHolder.tv_sale_goods_salecount=view.findViewById(R.id.tv_sale_goods_salecount);
            groupHolder.et_sale_goods_salecount=view.findViewById(R.id.et_sale_goods_salecount);
            groupHolder.img_sale_goods_add=view.findViewById(R.id.img_sale_goods_add);
            groupHolder.tv_price=view.findViewById(R.id.tv_price);
            groupHolder.tv_discount=view.findViewById(R.id.tv_discount);
            groupHolder.ll=view.findViewById(R.id.ll);
            view.setTag(groupHolder);
        }else{
            groupHolder= (GroupHolder) view.getTag();
        }

        final Goods goods=getGroup(i);
        if(goods!=null){
            int ticktGoodsInx =1;
            int ticktInx =1;
            if(goods.getTicktGoodsInx()!=null && goods.getTicktInx()!=null){
                ticktGoodsInx = Integer.parseInt(goods.getTicktGoodsInx());
                ticktInx = Integer.parseInt(goods.getTicktInx());
            }
            groupHolder.tv_number.setText((ticktGoodsInx+1)+"/"+(ticktInx+1));
            groupHolder.tv_name.setText(goods.getName());
            groupHolder.tv_price.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getSaleMoney())));
            groupHolder.tv_sale_goods_salecount.setText(goods.getSaleCount());   //显示数量
            groupHolder.tv_discount.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getDiscount())));//折扣

            View.OnClickListener itemListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()){
                        case R.id.img_sale_goods_add:  //加商品
                            Double goodCountAdd = Double.valueOf(goods.getSaleCount())+1;
//                            content = goods.getPrice() + "|" + goodCountAdd + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                            final QueryGoodParam param = new QueryGoodParam();
                            param.setBarcode(goods.getBarcode());
                            param.setCount(goodCountAdd+"");
                            param.setGoodsGuid(goods.getGoodsGuid());
                            param.setGoodsPrice(goods.getPrice());

                            fragment.queryFoodPresenter.queryGoods(param, fragment.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                            break;
                        case R.id.img_sale_goods_cut:  //减商品
                            if (Math.abs(Double.valueOf(goods.getSaleCount())) > 1){
                                Double goodCountCut = Double.valueOf(goods.getSaleCount())-1;
//                                content = goods.getPrice() + "|" + goodCountCut + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                                QueryGoodParam paramCut = new QueryGoodParam();
                                paramCut.setBarcode(goods.getBarcode());
                                paramCut.setCount(goodCountCut+"");
                                paramCut.setGoodsGuid(goods.getGoodsGuid());
                                paramCut.setGoodsPrice(goods.getPrice());

                                if(goodCountCut == 0){
                                    delectGood(goods);
                                }else{
                                    fragment.queryFoodPresenter.queryGoods(paramCut, fragment.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                                }
                            }else {
                                delectGood(goods);
                            }
                            break;

                        case R.id.tv_sale_goods_salecount://输入商品数量
                            InputNumberDialogCommon dialog = InputNumberDialogCommon.getInputNumberDialogCommon(context, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
                                @Override
                                public void InputDialogOnSubmitClick(String content) {
                                    try{
                                        Double goodStr = Double.parseDouble(content);
//                                        String goodCountStr = goods.getPrice() + "|" + content + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();

                                        QueryGoodParam param = new QueryGoodParam();
                                        param.setGoodsPrice(goods.getPrice());
                                        param.setBarcode(goods.getBarcode());
                                        param.setGoodsGuid(goods.getGoodsGuid());
                                        param.setCount(content);
                                        fragment.queryFoodPresenter.queryGoods(param, fragment.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                                    }catch (Exception e){
                                        ToastUtils.show("请输入正确的商品数量！");
                                    }
                                }
                            });
                            dialog.setIsCanInputPoint(true);
                            dialog.setTitle("商品数量");
                            dialog.setContent("请输入商品数量");
                            dialog.setEtHint("请输入商品数量");
                            dialog.showDialog(false);
                            break;
                        default:
                            break;
                    }

                }
            };

            groupHolder.img_sale_goods_add.setOnClickListener(itemListener);
            groupHolder.img_sale_goods_cut.setOnClickListener(itemListener);
            groupHolder.tv_sale_goods_salecount.setOnClickListener(itemListener);

        }
        return view;
    }

    @Override
    public View getChildView(final int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        ChildHolder childHolder;
        if(view==null){
            view= LayoutInflater.from(context).inflate(R.layout.item_food_order_child,null);
            childHolder=new ChildHolder();
            childHolder.tv_discount=view.findViewById(R.id.tv_discount);
            childHolder.tv_flavor=view.findViewById(R.id.tv_flavor);
            childHolder.tv_delete=view.findViewById(R.id.tv_delete);

            view.setTag(childHolder);
        }else{
            childHolder= (ChildHolder) view.getTag();
        }
        childHolder.tv_discount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFrontDiscountDialog(getGroup(i));
            }
        });
        childHolder.tv_flavor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFlavorDialog(getGroup(i));
            }
        });
        childHolder.tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delectGood(getGroup(i));
            }
        });
        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    class GroupHolder{
        private TextView tv_number;
        private TextView tv_name;
        private ImageView img_sale_goods_cut;
        private TextView tv_sale_goods_salecount;
        private EditText et_sale_goods_salecount;
        private ImageView img_sale_goods_add;
        private TextView tv_price;
        private TextView tv_discount;
        private LinearLayout ll;
    }

    class ChildHolder{
        private TextView tv_discount;
        private TextView tv_flavor;
        private TextView tv_delete;
    }


    public void setNewData(List<Goods> list){
        this.list=list;
        notifyDataSetChanged();
    }

    private void delectGood(final Goods goods) {
        SaleUtil.showInfoDialog(context,
                ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                ConstantString.DIALOG_MAIN_DELECT_GOOD_MESSAGE,
                new OnDialogListener() {
                    @Override
                    public void onClick(int flag) {
                        if (flag == DialogConstant.DIALOG_BTN_SURE) {
//                            String content2 = goods.getPrice() + "|" + "0" + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                            QueryGoodParam param = new QueryGoodParam();
                            param.setBarcode(goods.getBarcode());
                            param.setCount("0");
                            param.setGoodsGuid(goods.getGoodsGuid());
                            param.setGoodsPrice(goods.getPrice());
                            fragment.queryFoodPresenter.queryGoods(param, fragment.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                        }
                    }
                }
        );
    }

    public void setIndex(int index) {
        this.index = index;
        notifyDataSetChanged();
    }
    public void showFlavorDialog(final Goods goods){
        SelectFlavorDialog selectFlavorDialog=SelectFlavorDialog.getSelectFlavorDialog(context, new SelectFlavorDialog.SelectDialogOnClickListener() {
            @Override
            public void selectDialogOnClick(String flavor, String remarks, int position) {
//                String goodCountStr = goods.getPrice() + "|" + goods.getSaleCount() + "|" + goods.getBarCode() + "|"
//                        + goods.getGoodsGuid()+ "|" + flavor+ "|" + remarks;
                QueryGoodParam param = new QueryGoodParam();
                param.setGoodsPrice(goods.getPrice());
                param.setCount(goods.getSaleCount());
                param.setBarcode(goods.getBarcode());
                param.setGoodsGuid(goods.getGoodsGuid());
                param.setDesc(remarks);
                param.setTasteId(flavor);
                fragment.queryFoodPresenter.queryGoods(param, fragment.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
            }
        });

        selectFlavorDialog.setTitle("请选择您要的口味");
        List<CyFood.Flavor> flavors= goods.getFlavorList();
        if(flavors!=null&&flavors.size()>0) {
            selectFlavorDialog.showDialog(flavors, false);
        }else{
            ToastUtils.show("该餐品暂无口味!");
        }
    }


    /**
     * 前台折扣展示
     * @param goods
     */
    private void showFrontDiscountDialog(final Goods goods) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_goods_frontdiscount, null);
        TextView tvTitle = view.findViewById(R.id.tv_dialog_title_name);
        final SelfNumKeyView sf_containt = view.findViewById(R.id.member_soft_keyboard);

        tvTitle.setText("单品折扣");
        tvTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); //textview的drawableRight

        RadioButton rb_zkl = view.findViewById(R.id.rb_frontDiscount_zkl);//折扣率
        final RadioButton rb_zke = view.findViewById(R.id.rb_frontDiscount_zke);//折扣额
        TextView tv_payMoney = view.findViewById(R.id.tv_frontDiscount_payMoney);//应付金额
        final TextView tv_actuallyMoney = view.findViewById(R.id.tv_frontDiscount_actuallyMoney);//实付金额
        final TextView tv_discountType = view.findViewById(R.id.tv_zkType_name);//折扣名称
        final ImageView iv_discountRate = view.findViewById(R.id.iv_discountRate);//折扣率图片
        final EditText etDiscountRate = view.findViewById(R.id.et_frontDiscount_discountRate);//et折扣率
        final TextView tvDiscountRate = view.findViewById(R.id.tv_frontDiscount_discountRate);//et折扣率
        Button btnSure = view.findViewById(R.id.btn_frontDiscount_ok);//确定
        Button btnCancel = view.findViewById(R.id.btn_frontDiscount_cancel);//退出

        tv_payMoney.setText("￥"+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getSaleMoney()))+"");
        tv_actuallyMoney.setText("￥"+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getSaleMoney()))+"");

        rb_zke.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_discountType.setText("折扣金额");
                iv_discountRate.setVisibility(View.GONE);

            }
        });

        rb_zkl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_discountType.setText("折  扣  率");
                iv_discountRate.setVisibility(View.VISIBLE);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });

        etDiscountRate.setFocusable(false);
        sf_containt.setEnterReceptor(etDiscountRate);
        sf_containt.setIsCanInputPoint(true);
        sf_containt.setOnCallBack(new SelfNumKeyView.SelfNumCallBack() {
            @Override
            public void keyBoardSure(String num,String hint) {
                int zkje = 0;
                if(rb_zke.isChecked()){//折扣额
                    if(calculateFront(goods,1,num)!=null){
                        String actuallyMoney = MoneyUtils.getMabMoneyString(MoneyUtils.getSubtractMoney(goods.getSaleMoney(),calculateFront(goods,1,num)).toString());
                        tv_actuallyMoney.setText("￥"+ actuallyMoney +"");
//                        if(ErpCommonData.isFSTH)
//                            tv_actuallyMoney.setText("￥ -"+actuallyMoney);
                    }
                }else{//折扣率
                    if(calculateFront(goods,0,num)!=null){
                        String actuallyMoney = MoneyUtils.getMabMoneyString(MoneyUtils.getSubtractMoney(goods.getSaleMoney(),calculateFront(goods,0,num)).toString());
                        tv_actuallyMoney.setText("￥"+ actuallyMoney +"");
//                        if(ErpCommonData.isFSTH)
//                            tv_actuallyMoney.setText("￥ -"+actuallyMoney);
                    }
                }


            }
        });

        etDiscountRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtils.hideSoftInputButWithSelection(etDiscountRate,fragment.getActivity());
                etDiscountRate.setFocusable(true);
                etDiscountRate.setFocusableInTouchMode(true);
                etDiscountRate.requestFocus();
            }
        });

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                int disType =0;
                String discountInputContext = etDiscountRate.getText().toString();
                if(rb_zke.isChecked()){
                    disType =1;
//                    if(ErpCommonData.isFSTH)
//                        discountInputContext = "-"+discountInputContext;
                }else{
                    double tempDiscountRate = Double.valueOf(etDiscountRate.getText().toString())/10;
                    LogUtils.d("折扣率为："+tempDiscountRate);//服务端定义
                    discountInputContext = tempDiscountRate +"";
                }
                if(calculateFront(goods,disType,etDiscountRate.getText().toString()) !=null)
                    fragment.queryFoodPresenter.frontDiscount(disType+"",discountInputContext,goods,fragment.mTicketInfo.getOrderNo(),true);

            }
        });

        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setView(view).setCancelable(false).create();
        mDialog = dialog.show();
    }

    /**
     *  前台折扣请求和判断
     * @param goods  商品列表
     * @param disType  0是折扣率 1是折扣金额
     * @param discount  折扣金额或者折扣率
     */
    private String calculateFront(Goods goods,int disType,String discount){
        String zkje = "0";
        if (TextUtils.isEmpty(discount)||discount == null){
            return null;
        }
        if(disType == 0){//折扣率
            double tempDiscountRate = Double.valueOf(discount)/100;
            if (tempDiscountRate <= 0 || tempDiscountRate >= 1) {
                ToastUtils.showMsg("请输入正确折扣率", 0);
                return null;
            }
            zkje =  MoneyUtils.Double2Int(Double.parseDouble(goods.getSaleMoney()) * (1 - tempDiscountRate)) +"";
        }else {
            int tempDiscount = MoneyUtils.getMoneyInt(discount);
            int goodSumMoney = Math.abs(MoneyUtils.getMoneyInt(goods.getSaleMoney()));
            if(tempDiscount>goodSumMoney){
                ToastUtils.showMsg("折扣金额不能大于销售金额",0);
                return null;
            }
            zkje = MoneyUtils.getMoneyInt(discount) +"";
        }
        return zkje;
    }

}

